package com.bsf.mvc.interceptor;

import com.bsf.mvc.controller.NetController;
import com.bsf.mvc.template.SimpleTemplateProvider;
import com.bsf.mvc.template.TemplateProvider;
import com.bsf.serialization.json.JsonProvider;
import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于.net mvc 用法的兼容
 */
public class NetHandlerInterceptor implements HandlerInterceptor {

    /**
     * Handler执行完成之后调用这个方法
     */
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception exc)
            throws Exception {

    }

    /**
     * Handler执行之后，ModelAndView返回之前调用这个方法
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        if(handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;
            if (h.getBean() instanceof NetController) {
                NetController controller = (NetController)( h.getBean());
                if (modelAndView instanceof NetController.JsonResult)//json
                {
                    response.addHeader("Access-Control-Allow-Origin", "*");//跨域支持
                    response.setHeader("Content-Type", "application/json;charset=UTF-8");
                    NetController.JsonResult jsonResult = (NetController.JsonResult) modelAndView;
                    String json = new JsonProvider().serialize(jsonResult.Data);
                    response.getWriter().write(json);
                } else if (modelAndView instanceof NetController.ActionResult)//view
                {
                    //do nothing
                }
            }
        }
    }

    /**
     * Handler执行之前调用这个方法
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
//
        //页面模板扩展方法
        TemplateProvider tpl = new SimpleTemplateProvider();
        request.setAttribute("Html", tpl);
        return true;
    }

}